<template>
  <div class="app-container">
    <el-form :inline="true" :model="recordInfo.queryForm" class="demo-form-inline">
      <el-form-item label="订单编号">
        <el-input v-model="recordInfo.queryForm.orderNo" placeholder="订单编号" clearable style="width: 210px;" />
      </el-form-item>

      <el-form-item label="手机号">
        <el-input v-model="recordInfo.queryForm.mobile" @clear="clearMobile" placeholder="手机号" :maxlength="11" @input="handleMobileInput"
          clearable  style="width: 210px" />
      </el-form-item>

      <el-form-item label="充值类型">
        <el-select v-model="recordInfo.queryForm.topType" clearable placeholder="充值类型" style="width: 210px">
          <el-option v-for="item in rechargeTypeList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="充值优惠">
        <el-select v-model="recordInfo.queryForm.discountType" clearable placeholder="充值优惠" style="width: 210px">
          <el-option v-for="item in rechargeOfferList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="支付方式">
        <el-select v-model="recordInfo.queryForm.payType" clearable placeholder="支付方式" style="width: 210px">
          <el-option v-for="item in payMethodList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>


      <el-form-item label="订单状态">
        <el-select v-model="recordInfo.queryForm.orderState" clearable placeholder="订单状态" style="width: 210px">
          <el-option v-for="item in orderStatusList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <OrganizationSelector
        v-model="organizationQuery"
        :user-type="userInfo.organizationType"
      />


      <el-form-item label="创建时间">
        <el-date-picker v-model="createTimeValue" type="daterange" :picker-options="pickerOptions" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" :default-time="defaultTime"
          @change="dateChange('createTimeValue')" style="width: 300px" />
      </el-form-item>

      <!-- <el-form-item label="支付时间">
        <el-date-picker
          v-model="payTimeValue"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="defaultTime"
          @change="dateChange('payTimeValue')"
          style="width: 300px"
        />
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <div style="display: flex;justify-content: space-between;align-items: center; margin-bottom: 10px;" v-if=" recordInfo.list.length > 0">
      <h5 style="margin: 0; font-size: 16px;">订单列表</h5>
      <div class="statistics">
        <div class="statistics-item">
          实付金额：<span class="value">{{ recordInfo.list ? recordInfo.list[0].topMoneySum : '0.00' }}</span>
        </div>
        <div class="statistics-item">
          赠送总额：<span class="value">{{ recordInfo.list ? recordInfo.list[0].bonusMoneySum : '0.00' }}</span>
        </div>
      </div>
    </div>

    <el-table v-loading="recordInfo.loading" class="table-default" :data="recordInfo.list" border style="width: 100%"
      max-height="600">
      <el-table-column type="index" label="序号" width="60" align="center" />

      <el-table-column prop="orderNo" label="订单编号" width="190" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="viewOrderDetail(scope.row.memberRechargeOrderId)">{{ scope.row.orderNo
            }}</el-button>
        </template>
      </el-table-column>

      <el-table-column prop="topMoney" label="支付金额" width="100" align="center" />
      <el-table-column prop="bonusMoney" label="充值优惠" width="120" align="center">
        <template slot-scope="scope">
          <div style="text-align: center;font-size: 14px;" v-if="scope.row.topType === 1">
            <!-- top_type 是不是活动 -->
            <!-- discount_type 优惠类型   -->
            <div v-if="scope.row.discountType === 1">
              <div>赠送金额</div>
              <div>赠送{{ scope.row.bonusMoney }} 元</div>
            </div>
            <div v-else-if="scope.row.discountType === 2">
              <div>赠送礼品</div>
              <div>赠送礼品（价值{{ scope.row.giftValue }} 元）</div>
            </div>
            <div v-else  style="text-align: center;">
              <!-- 自定义充值 -->
              --
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="会员信息" align="center">
        <template slot-scope="scope">
          <div class="member-info-cell">
          <image-show :md5="scope.row.photoDownloadCode || ''" style="width:40px;height:40px;margin-right: 10px;" />
            <div class="member-text">
              <p class="name">{{ scope.row.userName }}</p>
              <p class="id-phone">ID: {{ scope.row.userId }}</p>
              <p class="id-phone">{{ scope.row.mobile }}</p>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="活动信息" align="center" width="180">
        <template slot-scope="scope">
          <div class="text-ellipsis">{{ scope.row.activityName }}</div>
          <span class="text-ellipsis">{{ scope.row.rechargeActivityId }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" width="140" align="center" />
      <el-table-column prop="orderStatusName" label="订单状态" width="80" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.orderState)">{{ scope.row.orderState ==
            '2' ? '已取消' : scope.row.orderState == 0 ?'待支付':'已支付' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="headquartersName" label="所属总部" align="center" />
      <el-table-column prop="chainName" label="所属连锁" align="center" />
      <el-table-column prop="organizationName" label="所属门店" align="center" />


      <!-- <el-table-column label="操作" fixed="right" width="80" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="goDetail(scope.row)">查看</el-button>
          <el-button v-if="scope.row.orderState === 1" type="text" size="small" @click="cancelOrder(scope.row)">取消</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="recordInfo.total > 0" :total="recordInfo.total" :page.sync="recordInfo.queryForm.page"
      :limit.sync="recordInfo.queryForm.pageSize" @pagination="getRecordList" :page-sizes="[10, 20, 50, 100]" />
    <order-detail-dialog :visible.sync="showDetailDialog" :order-id="memberRechargeOrderId" />
  </div>
</template>
<script>
import OrganizationSelector from '@/views/member/components/OrganizationSelector.vue'
// MemberOrderList.vue
import { mapGetters } from 'vuex'
import filters from '@/filters/index'
import ListMixin from '@/mixins/modules/list'
import messageMixin from '@/mixins/modules/message'
import Pagination from '@/components/Pagination'
import OrderDetailDialog from './components/OrderDetailDialog.vue'
import imageShow from '@/components/imageShow'
export default {
  components: {
    OrganizationSelector,
    OrderDetailDialog,
    imageShow,
    Pagination
  },
  filters: { ...filters },
  // 混入 ListMixin
  mixins: [ListMixin, messageMixin],
  data() {
    return {
      showDetailDialog: false,
      memberRechargeOrderId: null,
      // 绑定到日期选择器的值
      createTimeValue: null,
      payTimeValue: null,

      // 页面统计数据
      statistics: {
        totalOrderCount: 100, // 订单总数
        totalActualPay: '100000.00', // 实付总金额
        totalGiftAmount: '20000.00' // 赠送总额
      },

      recordInfo: {
        queryForm: {
          page: 1,
          pageSize: 10,
          orderBy: 'createTimeDesc',
          // 查询表单字段
          orderNo: '',
          mobile: '',
          topType: '',
          userId: '',
          discountType: '',
          payType: '',
          headquartersId: '',
          chainId: '',
          storeId: '',
          orderState: '',
        },
        requestUrl: this.$api.getStoreRechargeList,
        list: [],
        total: 0,
        loading: false
      },

      rechargeTypeList: [{ name: '按活动充值', value: 1 }, { name: '自定义充值', value: 2 }],
      rechargeOfferList: [{ name: '赠送金额', value: 1 }, { name: '赠送礼品', value: 2 }],
      payMethodList: [
        { name: '在线支付', value: 1 },
        { name: '扫码枪B扫C', value: 2 },
        { name: '现金支付', value: 3 },
        { name: '微信线下转账', value: 4 },
        { name: '支付宝线下转账', value: 5 }
      ],
      orderStatusList: [
        { name: '已取消', value: 2, tag: 'info' },
        { name: '待支付', value: 0, tag: 'success' },
        { name: '已支付', value: 1, tag: 'danger' }
      ],

      changeDateNameInfo: {
        createTimeValue: ['orderStartTime', 'orderEndTime'],
        payTimeValue: ['payTimeStart', 'payTimeEnd']
      },

      getListCallback: (res) => {
        if (res.list && res.list.length > 0) {
          res.list.forEach(item => {
            // 1. 格式化时间
            item.createTime = this.$commonUtils.getShowTime(item.createTime) // 假设存在
            item.payTime = this.$commonUtils.getShowTime(item.payTime) // 假设存在

            // 2. 订单状态映射
            const statusItem = this.orderStatusList.find(s => s.value === item.orderState)
            item.orderStatusName = statusItem ? statusItem.name : '未知状态'

            item.topMoneySum = ' ¥' + this.$amountUtils.getYuan(item.topMoneySum)
            item.bonusMoneySum = ' ¥' + this.$amountUtils.getYuan(item.bonusMoneySum)
            item.topMoney = ' ¥' + this.$amountUtils.getYuan(item.topMoney)
            item.bonusMoney = ' ¥' + this.$amountUtils.getYuan(item.bonusMoney)
            item.giftValue = ' ¥' + this.$amountUtils.getYuan(item.giftValue)
            // 4. 模拟会员信息（设计稿中的数据）
            if (!item.memberAvatar) {
              item.memberAvatar = '/static/default-avatar.png' // 默认头像
            }
          })
        }
        // 列表数据赋值和总数更新由 ListMixin 完成
        this.recordInfo.list = res.list || []
      },

      beforeRequest: () => {
        // 由于 Mixin 的 changeDate 逻辑较为完善，这里直接调用即可
        this.changeDate(this.createTimeValue, 'createTimeValue')
        this.changeDate(this.payTimeValue, 'payTimeValue')

        // 确保 returnCount 逻辑正确
        this.recordInfo.queryForm.returnCount = this.recordInfo.queryForm.page === 1

        // 可选：添加其他查询前的校验逻辑
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    organizationQuery: {
      get() {
        return {
          headquartersId: this.recordInfo.queryForm.headquartersId,
          chainId: this.recordInfo.queryForm.chainId,
          storeId: this.recordInfo.queryForm.storeId,
        };
      },
      set(newVal) {
        this.recordInfo.queryForm.headquartersId = newVal.headquartersId;
        this.recordInfo.queryForm.chainId = newVal.chainId;
        this.recordInfo.queryForm.storeId = newVal.storeId;
      }
    }
  },
  // Mixin 的 created 中已经调用了 getRecordList()

  methods: {
    clearMobile() {
      this.recordInfo.queryForm.mobile = '';
      this.recordInfo.queryForm.userId = '';
    },
    handleMobileInput(value) {
      const mobileNumber = value.trim();
      if (mobileNumber.length === 11) {
        console.log('手机号大于七位，触发查询请求:', mobileNumber);
        this.$api.getMemberInfoList({
          returnUserDetail: true,
          returnCount: false,
          orderBy: 'createTimeDesc',
          mobile: mobileNumber,
          pageSize: 100,
          page: 1
        }).then(response => {
            console.log('查询结果:', response.list);
            if (response.list && response.list.length > 0) {
              this.recordInfo.queryForm.userId = response.list[0].userId;
            }else{
            this.recordInfo.queryForm.userId = '999999999'; // 设置一个不存在的用户ID，确保查询无结果
          }
            // 处理查询结果
          })
          .catch(error => {
            console.error('查询出错:', error);
          });
      }
    },
    viewOrderDetail(memberRechargeOrderId) {
      console.log('打开订单详情，订单ID:', memberRechargeOrderId)
      this.memberRechargeOrderId = memberRechargeOrderId // 传入订单ID
      this.showDetailDialog = true       // 显示弹窗
    },
    // 根据订单状态获取 El-Tag 的主题
    getStatusTagType(status) {
      const statusMap = {
        0: 'info', // 待支付 -> 蓝色/灰色
        1: 'success', // 已支付 -> 绿色
        2: 'danger', // 已取消 -> 红色
      }
      return statusMap[status] || 'info'
    },

    // 查询按钮，利用 Mixin 的 getRecordList
    search() {
      this.recordInfo.queryForm.page = 1
      this.getRecordList()
    },

    // 重置表单，清空所有查询条件
    resetForm() {
      // 业务字段清空
      this.recordInfo.queryForm = {
        page: 1,
        pageSize: 10,
        orderBy: 'createTimeDesc',
        orderNo: '',
        mobile: '',
          userId: '',
        topType: '',
        discountType: '',
        payType: '',
        headquartersId: '', // 清空
    chainId: '',        // 清空
    storeId: '',        // 清空
        orderState: '',
      }
      // 日期清空
      this.createTimeValue = null
      this.payTimeValue = null
      // 重新查询
      this.search()
    },

    // 模拟取消订单
    cancelOrder(item) {
      this.$confirm(`确定要取消订单【${item.orderNo}】吗?`, '提示', {
        type: 'warning'
      }).then(() => {
        // 调用取消订单接口
        this.$message.success('取消成功！')
        this.getRecordList() // 刷新列表
      }).catch(() => { })
    }

  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.demo-form-inline {
  padding-bottom: 5px;

  // 保持查询表单项之间的间距和对齐
  .el-form-item {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

// 统计信息样式
.statistics {
  display: flex;
  justify-content: flex-end;
  font-size: 14px;
  color: #606266;

  .statistics-item {
    margin-left: 20px;
  }

  .value {
    color: #F07505; // 采用你之前代码中的高亮色
    font-weight: bold;
    font-size: 16px;
  }
}

// 表格内会员信息单元格样式
.member-info-cell {
  display: flex;
  align-items: center;

  .avatar-sm {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 8px;
    object-fit: cover;
    border: 1px solid #eee;
  }

  .member-text {
    text-align: left;

    p {
      margin: 0;
      line-height: 1.2;
    }

    .name {
      font-weight: bold;
      color: #333;
    }

    .id-phone {
      font-size: 12px;
      color: #999;
    }
  }
}

// 表格内容省略号
.text-ellipsis {
  display: block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

// 使金额列右对齐
::v-deep .el-table {
  .el-table__cell:nth-child(3) {

    // 实付金额列 (第3列)
    .cell {
      text-align: right;
    }
  }
}
</style>
